from channels.generic.websocket import AsyncWebsocketConsumer
from channels.db import database_sync_to_async
from django.db.models import Q
from api import models
import json


class ChatConsumer(AsyncWebsocketConsumer):
    """处理通知应用中的WebSocket请求"""

    async def connect(self):
        # 用户
        self.user = self.scope['user']

        self.room_name = self.user.id
        # 聊天组
        self.room_group_name = 'chat_%s' % self.room_name

        """建立连接"""
        if self.user == "AnonymousUser":
            # 未登录用户拒绝连接
            await self.close()
        else:
            # 创建一个组
            await self.channel_layer.group_add(
                self.room_group_name,
                self.channel_name
            )
            await self.accept()

    async def receive(self, text_data):
        """将接收到的消息返回给前端"""
        text_data_json = json.loads(text_data)

        # Send message to room group
        await self.channel_layer.group_send(
            self.room_group_name,
            {
                'type': 'chat.message',
                'message': text_data_json
            }
        )

    async def disconnect(self, code):

        await self.channel_layer.group_discard(
            self.room_group_name,
            self.channel_name
        )

    async def chat_message(self, event):
        message = event['message']

        await self.send(text_data=json.dumps({
            'message': message
        }))


class SendConsumer(AsyncWebsocketConsumer):
    async def connect(self):
        # 用户
        self.user = self.scope['user']

        self.room_name = self.scope['url_route']['kwargs']['room_name']
        # 聊天组
        self.room_group_name = 'chat_%s' % self.room_name

        print(self.room_group_name)
        """建立连接"""
        if self.user == "AnonymousUser":
            # 未登录用户拒绝连接
            await self.close()
        else:
            # 创建一个组
            await self.channel_layer.group_add(
                self.room_group_name,
                self.channel_name
            )
            await self.get_unread()
            await self.accept()

    async def receive(self, text_data):

        """将接收到的消息返回给前端"""
        text_data_json = json.loads(text_data)
        # Send message to room group
        await self.channel_layer.group_send(
            self.room_group_name,
            {
                'type': 'chat.message',
                'message': text_data_json
            }
        )

    async def disconnect(self, code):

        """断开连接"""
        await self.channel_layer.group_discard(
            self.room_group_name,
            self.channel_name
        )

    async def chat_message(self, event):
        message = event['message']
        await self.get_news(message)
        # Send message to WebSocket
        await self.send(text_data=json.dumps({
            'message': message
        }))

    @database_sync_to_async
    def get_news(self, msg):
        news_object = \
            models.News.objects.filter(
                Q(user_id=msg['user'], receive_user_id=self.room_name) |
                Q(user_id=self.room_name, receive_user_id=msg['user'])).order_by('-create_date')[0]
        unread = news_object.unread + 1
        models.News.objects.create(user_id=msg['user'], content=msg['content'], type=msg['type'],
                                   create_date=msg['create_date'], receive_user_id=msg['receive_user'],
                                   unread=unread)

    @database_sync_to_async
    def get_unread(self):
        news_object = models.News.objects.filter(user_id=self.room_name).order_by('-create_date')[0]
        news_object.unread = 0
        news_object.save()
